const { userAlreadyExists, userFormatError, userDoesNotExist, userLoginError, userPasswordError } = require("../constant/error.type")
const { getUserInfo } = require("../service/user.service")
const bcrypt = require('bcryptjs');
/**验证用户信息是否为空 */
const userValidtor = async (ctx, next) => {
  const { user_name, password } = ctx.request.body
  // 判断请求体是否为空，验证合法性
  if (!user_name || !password) {
    // 记录错误日志
    console.error(userFormatError.message, ctx.request.body)
    ctx.app.emit('error', userFormatError, ctx)
    return
  }
  await next()
}
/**判断用户是否存在 */
const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body
  if (await getUserInfo({ user_name })) {
    console.error(userAlreadyExists.message, ctx.request.body)
    ctx.app.emit('error', userAlreadyExists, ctx)
    return
  }
  await next()
}
/**判断用户登录 */
const verifyUserLogin = async (ctx, next) => {
  const { user_name, password } = ctx.request.body
  // 1.判断用户是否存在
  try {
    const res = await getUserInfo({ user_name })
    if (!res) {
      console.error(userDoesNotExist.message, ctx.request.body)
      ctx.app.emit('error', userDoesNotExist, ctx)
      return
    }
    // 2.判断用户密码是否匹配
    if (!bcrypt.compareSync(password, res.password)) {
      console.error(userPasswordError.message, ctx.request.body)
      ctx.app.emit('error', userPasswordError, ctx)
      return
    }
    // 存储当前登录用户信息,避免重复查询数据库
    ctx.user = res
  } catch (error) {
    console.error(userLoginError.message, ctx.request.body)
    ctx.app.emit('error', userLoginError, ctx)
    return
  }

  await next()
}
module.exports = {
  userValidtor,
  verifyUser,
  verifyUserLogin
}